/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gui.logado.chat;

import java.io.DataInputStream;
import java.io.IOException;
import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.ImageItem;
import recados.Recados;

/**
 *
 * @author SILVA
 */
public class ImageLoader {

    private Vector imgs;
    private Vector urls;

    public ImageLoader() {
        imgs = new Vector(1);
        urls = new Vector(1);
    }

    public void carrega(final ImageItem item, final String url) {
        new Thread(new Runnable() {

            public void run() {

                if (url.startsWith("http://") && Recados.getInstance().getConfig().isImagensChat()) {

                    if (urls.contains(url)) {
                        int index = urls.indexOf(url);
                        item.setImage((Image) imgs.elementAt(index));
                        return;
                    }

                    try {
                        HttpConnection conn = (HttpConnection) Connector.open(url);
                        DataInputStream imagem = conn.openDataInputStream();
                        item.setImage(Image.createImage(imagem));
                    } catch (IOException ex) {
                        item.setAltText(".img.");
                    }

                    urls.addElement(url);
                    imgs.addElement(item.getImage());

                    return;
                }

                if (url.endsWith(".png") && Recados.getInstance().getConfig().isSmilesChat()) {
                    try {
                        item.setImage(Image.createImage("/smiles/" + url));
                    } catch (IOException ex) {
                        item.setAltText(".img.");
                    }
                }
            }
        }).start();
    }
}
